package com.edu.zut.service.Impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.zut.entity.Paper;
import com.edu.zut.mapper.PaperMapper;
import com.edu.zut.mapper.UserMapper;
import com.edu.zut.result.HttpCode;
import com.edu.zut.result.ResponseResult;
import com.edu.zut.service.PaperService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileOutputStream;

/**
 * <p>
 * 学生论文表 服务实现类
 * </p>
 *
 * @author 许文科
 * @since 2023-01-12
 */
@Service
@Transactional
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements PaperService {

    @Value("${papers}")
    private String papers;

    @Resource
    private PaperMapper paperMapper;
    @Resource
    private UserMapper userMapper;


    @Override
    public ResponseResult uploadPaper(MultipartFile file) {

        if (file == null) {
            return new ResponseResult(HttpCode.ERROR, "文件为空", null);
        }

        //如果存在
        if (FileUtil.exist(papers + "//" + file.getOriginalFilename())) {
            FileUtil.del(papers + "//" + file.getOriginalFilename());
        }

        // 获取文件名(包括后缀)
        String fileName = file.getOriginalFilename();
        try (FileOutputStream fos = new FileOutputStream(papers + "//" + fileName)) {
            fos.write(file.getBytes());

            String username = (String) SecurityContextHolder
                    .getContext().getAuthentication().getPrincipal();
            Long userId = userMapper.getUserIdByUserName(username);
            //保存文件路径到数据库
            Paper paper = new Paper();
            paper.setUserId(userId);
            paper.setPaperPath(papers + "\\" + fileName);
            paper.setPaperName(fileName);
            paperMapper.insert(paper);

            return new ResponseResult(HttpCode.SUCCESS, "上传成功.", papers + "\\" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(HttpCode.ERROR, "上传失败.", null);
        }
    }
}
